package org.example.Handler;

import io.netty.channel.ChannelHandlerContext;
import org.example.Command.FileMessage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public interface SendFile {
    static void sendFile(ChannelHandlerContext ctx, File file, File filePath, Integer sequenceId) throws IOException {
        //文件创建
        FileMessage fileUploadFile = new FileMessage(file);
        String fileMd5 = file.getName();// 文件名
        fileUploadFile.setFile_md5(fileMd5);
        fileUploadFile.setStarPos(0);// 文件开始位置
        fileUploadFile.setFilePath(filePath);
        fileUploadFile.setSequenceId(sequenceId);//序列号，作为标识同一次文件传输的标志

        //只读模式打开文件
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileUploadFile.getFile(), "r");
        randomAccessFile.seek(fileUploadFile.getStarPos());
        byte[] bytes = new byte[1024];
        int byteRead = randomAccessFile.read(bytes);
        fileUploadFile.setEndPos(byteRead);// 文件结束
        while (byteRead != -1) {
//            System.out.println(byteRead);
            fileUploadFile.setBytes(bytes);
            fileUploadFile.setEndPos(byteRead + fileUploadFile.getStarPos());
            ctx.writeAndFlush(fileUploadFile);
            fileUploadFile.setStarPos(fileUploadFile.getEndPos());
            byteRead = randomAccessFile.read(bytes);
        }
        System.out.println(fileMd5 + "发送完毕");
    }
}
